package ch.usi.inf.pf2.textediter;


import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;



// I used this websight http://docstore.mik.ua/orelly/java/awt/ch20_04.html
//http://www.javaworld.com/javaworld/javatips/jw-javatip61.html
//http://java.sun.com/developer/technicalArticles/releases/data/

public class Edit extends Frame 
{

	private TextField tf;
	private TextArea ta;

	

		public Edit() {

		add(tf = new TextField(), "North");
		add(ta = new TextArea(), "Center");
		MenuBar mb = new MenuBar();
		mb.add(makeEditMenu());
		setMenuBar(mb);
		setSize(250, 250);}
	
	

	public void copy()
	{
		//A class which implements a mechanism to transfer data using cut/copy/paste operations.
		Clipboard clipboard = getToolkit().getSystemClipboard();
		//Constructs a StringSelection object from the given string.
		StringSelection data = new StringSelection(tf.getText());
		// Sets the current contents of the clipboard to the specified transferable object and registers 
		//the specified clipboard owner as the owner of the new contents.
		clipboard.setContents(data, data);

	}

	public void Delete()
	{

		tf.setText("");
	}
	public void paste()
	{
		Clipboard clipboard = getToolkit().getSystemClipboard();
		Transferable clipData = clipboard.getContents(this);
		String s;
		try {
			s = (String) (clipData.getTransferData(DataFlavor.stringFlavor));
		} 
		catch (Exception ex) {
			s = ex.toString();
		}
		ta.setText(s);
	}

	public void cut()
	{
		Clipboard clipboard = getToolkit().getSystemClipboard();
		StringSelection data = new StringSelection(tf.getText());
		clipboard.setContents(data, data);
		tf.setText("");
	}


	private Menu makeEditMenu() {

		JFrame frame=new JFrame("Edit");

		Menu editMenu = new Menu("Edit");
		MenuItem mi = new MenuItem("Cut");
		mi.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e)
			{

				cut();
			}});
		editMenu.add(mi);
		mi = new MenuItem("Copy");
		mi.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e)
			{

				copy();
			}});

		editMenu.add(mi);
		mi = new MenuItem("Paste");
		mi.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e)
			{

				paste();
			}});
		editMenu.add(mi);
		mi = new MenuItem("Delete");
		mi.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e)
			{
				Delete();
			}});
		editMenu.add(mi);

		return editMenu;

	}

	public static void main(String[] args) {
		new Edit().show();
	}

}